import random
# from datetime import datetime # 原来用的注释掉
from django.utils import timezone as datetime # 不想大面积修改就这么做
from django.http import JsonResponse
from myadmin.models import User


def index(request):
    '''浏览信息'''
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    qs = User.objects.filter(status__gt=0)  # 状态大于0
    # 将 QuerySet 对象 转化为 list 类型
    # 否则不能 被 转化为 JSON 字符串
    # retlist = list(qs.values())

    list = []
    for user in qs:
        list.append(user.toDict())

    return JsonResponse({'state': 1, 'msg': list})



def insert(request):
    '''执行添加'''
    uname = request.POST.get('username')
    if User.objects.filter(username=uname).exists():
        ob = User.objects.get(username=uname)
        if ob.status == 0:
            ob.status = 1
            ob.nickname = request.POST.get('nickname')
            # 获取密码并md5
            import hashlib
            md5 = hashlib.md5()
            n = random.randint(100000, 999999)
            s = request.POST['password'] + str(n)  # 从表单获取密码并添加干扰值
            md5.update(s.encode('utf-8'))  # 将要产生md5的字串放进去
            ob.password_hash = md5.hexdigest()  # 获取md5值
            ob.password_salt = n
            ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.save()
            return JsonResponse({'state': 1, 'msg': '添加成功'})
        else:
            return JsonResponse({'state': 0, 'msg': '账户已存在'})
    else:
        try:
            ob = User()
            ob.username = uname
            ob.nickname = request.POST.get('nickname')
            # 获取密码并md5
            import hashlib
            md5 = hashlib.md5()
            n = random.randint(100000, 999999)
            s = request.POST.get('password') + str(n)  # 从表单获取密码并添加干扰值
            md5.update(s.encode('utf-8'))  # 将要产生md5的字串放进去
            ob.password_hash = md5.hexdigest()  # 获取md5值
            ob.password_salt = n

            ob.status = 1
            ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.save()
            context = {'state': 1, 'msg': '添加成功'}
        except Exception as err:
            print(err)
            context = {'state': 0, "msg": "添加失败"}
        return JsonResponse(context)


def delete(request, uid):
    '''删除信息'''
    try:
        ob = User.objects.get(id=uid)
        ob.status = 0
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'state': 1, "msg": "已删除"}
    except Exception as err:
        print(err)
        context = {'state': 0, "msg": "删除失败"}

    return JsonResponse(context)
    # return render(request, "myadmin/info.html", context)


def update(request, uid):
    '''执行编辑'''
    try:
        ob = User.objects.get(id=uid)
        # ob.nickname = request.POST.get('nickname')
        ob.status = request.POST.get('status')
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'state': 1, "msg": "修改成功！"}
    except Exception as err:
        print(err)
        context = {'state': 0, "msg": "修改失败"}
    return JsonResponse(context)


def resetpass(request, uid):
    '''重置密码'''
    try:
        ob = User.objects.get(id=uid)
        # 获取密码并md5
        import hashlib
        md5 = hashlib.md5()
        n = random.randint(100000, 999999)
        s = request.POST['password'] + str(n)
        md5.update(s.encode('utf-8'))
        ob.password_hash = md5.hexdigest()
        ob.password_salt = n
        ob.save()
        context = {'state': 1, 'msg': "密码重置成功"}
    except Exception as err:
        print(err)
        context = {'state': 0, "msg": "密码重置失败"}
    return JsonResponse(context)
